package com.baidu.iit.pxp.handler;

import com.baidu.iit.pvm.delegate.Condition;
import com.baidu.iit.pvm.process.ActivityImpl;
import com.baidu.iit.pvm.process.ScopeImpl;
import com.baidu.iit.pvm.process.TransitionImpl;
import com.baidu.iit.pxp.el.UelExpressionCondition;
import com.baidu.iit.pxp.model.BaseElement;
import com.baidu.iit.pxp.model.SequenceFlow;
import com.baidu.iit.pxp.parser.BpmnParse;
import org.apache.commons.lang3.StringUtils;

/**
 * User: huangweili
 * Date: 14-4-30
 * Time: 上午9:53
 */
public class SequenceFlowParseHandler extends AbstractBpmnParseHandler<SequenceFlow> {

    public static final String PROPERTYNAME_CONDITION = "condition";
    public static final String PROPERTYNAME_CONDITION_TEXT = "conditionText";

    public Class< ? extends BaseElement> getHandledType() {
        return SequenceFlow.class;
    }

    protected void executeParse(BpmnParse bpmnParse, SequenceFlow sequenceFlow) {

        ScopeImpl scope = bpmnParse.getCurrentScope();

        ActivityImpl sourceActivity = scope.findActivity(sequenceFlow.getSourceRef());
        ActivityImpl destinationActivity = scope.findActivity(sequenceFlow.getTargetRef());

        TransitionImpl transition = sourceActivity.createOutgoingTransition(sequenceFlow.getId());
        bpmnParse.getSequenceFlows().put(sequenceFlow.getId(), transition);
        transition.setProperty("name", sequenceFlow.getName());
        transition.setProperty("documentation", sequenceFlow.getDocumentation());
        transition.setDestination(destinationActivity);
        if (StringUtils.isNotEmpty(sequenceFlow.getConditionExpression())) {
            Condition expressionCondition = new UelExpressionCondition(bpmnParse.getExpressionManager().createExpression(sequenceFlow.getConditionExpression()));
            transition.setProperty(PROPERTYNAME_CONDITION_TEXT, sequenceFlow.getConditionExpression());
            transition.setProperty(PROPERTYNAME_CONDITION, expressionCondition);
        }

        createExecutionListenersOnTransition(bpmnParse, sequenceFlow.getExecutionListeners(), transition);

    }

}
